<script setup lang="ts">
import type { TCategoryItem } from '@/api/roles'
const props = defineProps<{
  category: TCategoryItem
}>()
const emit = defineEmits<{
  (e: 'postCheckedIdsRef', payload: Ref<number[]>): void
}>()
// 所有备选项目
const cities: number[] = []
// 所有已选项
const checkedCities = ref<number[]>([])
// 遍历category 填充 cities checkedCities
props.category.resourceList?.forEach((resource) => {
  cities.push(resource.id)
  resource.selected && checkedCities.value.push(resource.id)
})
// indeterminate true 半选不确定状态
const isIndeterminate = ref(checkedCities.value.length > 0 && checkedCities.value.length < cities.length)

// 全选 / 全不选
const checkAll = ref(checkedCities.value.length === cities.length)
// 监听 当组内没有项被选中时候，将全选/全不选 设置为false
watchEffect(() => {
  if (checkedCities.value.length == 0) {
    checkAll.value = false
    isIndeterminate.value = false
  }
})
// 全选方法
const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? cities : []
  isIndeterminate.value = false
}
// 单选项目方法
const handleCheckedCitiesChange = (value: number[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === cities.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.length
}
// 和父组件通讯
emit('postCheckedIdsRef', checkedCities)
</script>
<template>
  <div class="container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange(checkAll)">
            {{ props.category.name }}</el-checkbox
          >
        </div>
      </template>
      <el-row>
        <el-col :span="8" v-for="resource in category.resourceList" :key="resource.id">
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange(checkedCities)">
            <el-checkbox :label="resource.id">{{ resource.name }}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<style scoped lang="scss">
.container {
  color: #000;
  .el-card {
    margin-bottom: 20px;
  }
}
</style>
